package com.baiytfp.hf.HFDataExchange.action.service;

import com.baiytfp.hf.baiytfp.framework.base.BaseService;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;
import com.baiytfp.hf.baiytfp.hfutils.HFMap;
import com.baiytfp.hf.baiytfp.hfutils.HFString;
import com.baiytfp.hf.HFDataExchange.action.dao.MenuDAOImpl;
import com.baiytfp.hf.HFDataExchange.action.dao.TreeDAOImpl;
import com.baiytfp.hf.HFDataExchange.common.model.base.HFSysParams;
import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.table.Tree;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_account;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_info;
import com.baiytfp.hf.HFDataExchange.common.model.vo.TreeVO;
import com.baiytfp.hf.HFDataExchange.common.utils.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Steven-HF on 2017/5/13.
 */

@Service
public class TreeService extends BaseService {

	@Resource(name= HFSysParams.DB_TYPE + "TreeDAOImpl")
	private TreeDAOImpl treeDAO;


	public TreeService() throws Exception {

	}

	// 读取树（管理页面所使用)
	public String getTypeTreeJSON(String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		if (sWhere.length() > 0) {
			sWhere.append(" and ");
		}
		sWhere.append(" TREE_TYPE = ?");
		params.add(treeType);

		String orderBy = " order by node_deep desc, parent_tree_code, node_order asc ";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List<Tree> list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class,
				params.toArray());

		// 保存结果使用
		StringBuffer jsonSbr = new StringBuffer();
		// 临时数组（用于保存子结点信息）
		Map map_tempChild = new HashMap();
		// 临时父结点
		String tempParent = "null";

		Iterator<Tree> it = list.iterator();
		while (it.hasNext()) { // 遍历列表（树节点）
			Tree treeVO = it.next();

			// 判断是否是同一个父节点
			if (!tempParent.equals(treeVO.getParent_tree_code())) {
				/*
				 * 若不是同一个你节点，则先把之前所有的HTML存入 map, 清空 html, 更新父节点
				 */
				if (!"null".equals(tempParent)) {
					map_tempChild.put(tempParent, jsonSbr.toString());
				}
				jsonSbr.delete(0, jsonSbr.length());
				tempParent = treeVO.getParent_tree_code();
			} else {
				jsonSbr.append(",");
			}
			jsonSbr.append("{");
			jsonSbr.append("\"attributes\": { \"id\" : \"" + treeVO.getId() + "\",");
			jsonSbr.append("\"treeCode\":\"" + treeVO.getTree_code() + "\",");
			jsonSbr.append("\"nodeDeep\":\"" + treeVO.getNode_deep() + "\", ");
			jsonSbr.append("\"parentTreeCode\":\"" + treeVO.getParent_tree_code() + "\", ");
//			jsonSbr.append("\"nodeUrl\": \"" + treeVO.getNode_url() + "\" ");
			jsonSbr.append("}, ");

			jsonSbr.append("\"data\":{\"title\":\"" + treeVO.getNode_name() + "\"},");

			if ("-1".equals(treeVO.getParent_tree_code())) { // 顶级结点
				jsonSbr.append("\"state\" :\"open\" ");
			} else {
				jsonSbr.append("\"state\" :\"leaf\" ");
			}

			// children
			if (treeVO.getChildren_number() > 0 && map_tempChild.get(treeVO.getTree_code()) != null) { // 是否有子节点
				// 如果有子节点，则把子节点的 HTML 加入本节点
				jsonSbr.append(", \"children\" : [");
				jsonSbr.append(HFMap.getIstance().getString(map_tempChild, treeVO.getTree_code()));
				jsonSbr.append("]");
			}
			jsonSbr.append("}");
		}

		return jsonSbr.toString();
	}

	// 读取树（前台页面所使用)
	public String getTypeTreeJSONShow(String treeType, boolean hasAuth, String userCode) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE + " t1 ");

		if (sWhere.length() > 0) {
			sWhere.append(" and ");
		}
		sWhere.append(" TREE_TYPE=? and (IS_OPEN=1 OR IS_OPEN IS NULL) ");
		params.add(treeType);

		// 判断是否为超级管理员，如果为否，则加上访问限制，只有设置了权限的结点才能查看
		if (hasAuth && !UserUtil.isAdmin(userCode)) {

			User_account usersAccountVO = UserUtil.getUsersAccount(userCode);
			User_info userInfoVO = UserUtil.getUserInfo(userCode);

			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" exists (select 1 from (select node_seq, max(is_auth) as a, max(is_disabled) as d from "
					+ TableName.AUTH);
			sWhere.append("  where TREE_TYPE=? ");
			sWhere.append(" and ((OBJ_TYPE = 1 and OBJ_CODE=?) ");
//			if (!"".equals(StringUtil.getString(userVO.getUser_role()))) { // 当存在角色时，查询角色
//				sWhere.append(" OR (OBJ_TYPE = 3 and OBJ_CODE in (" + UserUtil.getSqlRoleCode(userVO.getUser_role())
//						+ ")) ");
//			}
//			if (userInfoVO != null && !"".equals(StringUtil.getString(userInfoVO.getDept_seq_code()))) { // 当存在部门时，
//				// 查询部门
//				sWhere.append(" OR (OBJ_TYPE=2 and OBJ_CODE in ("
//						+ UserUtil.getSqlDeptCode(userInfoVO.getDept_seq_code()) + "))  ");
//			}

			//用户标签
//			Sh_user_info shUserInfo = HFDBHelper.read(TableName.SH_USER_INFO, " where user_code = ? ", Sh_user_info.class, userCode);
//			if (!"".equals(StringUtil.getString(shUserInfo.getTags()))) { // 当存在角色时，查询角色
//				sWhere.append(" OR (OBJ_TYPE = 4 and OBJ_CODE in (" + UserUtil.getSqlRoleCode(shUserInfo.getTags())
//						+ ")) ");
//			}

			sWhere.append("  ) group by node_seq) t2 where t2.node_seq=t1.seq and t2.a=1 and t2.d<>1 or t2.d is null)   ");

			params.add(treeType);
			params.add(userCode);
		}

		String orderBy = " order by node_deep desc, parent_tree_code, node_order asc ";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}

		List<TreeVO> list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, TreeVO.class,
				params.toArray());

		// 保存结果使用
		StringBuffer json = new StringBuffer();//new StringBuffer("{\"title\": \"系统菜单\",\"children\": [");
		List<TreeVO> rootTrees = new ArrayList<TreeVO>();
		for (TreeVO tree : list) {
			if ("-1".equals(tree.getParent_tree_code())) {
				rootTrees.add(tree);
			}
			for (TreeVO t : list) {
				if (t.getParent_tree_code().equals(tree.getTree_code())) {
					if (tree.getChildList() == null) {
						List<TreeVO> myChildrens = new ArrayList<TreeVO>();
						myChildrens.add(t);
						tree.setChildList(myChildrens);
					} else {
						tree.getChildList().add(t);
					}
				}
			}
		}
		json.append(appendJson(rootTrees));
		if (json.toString().endsWith(",")) {
			json = new StringBuffer(json.subSequence(0, json.length() - 1));
		}
//		json.append("]}");
		return json.toString();
	}

	private StringBuffer appendJson(List<TreeVO> treeList) {
		StringBuffer json = new StringBuffer();
		for (TreeVO tree : treeList) {
			json.append("{\"title\":\"" + tree.getNode_name() + "\", ");
//			json.append("\"href\":\"" + tree.getNode_url() + "\",");

//			if (tree.getIs_quick() == 1) { // 是否用于打开新窗口
//				json.append("\"target\":\"_blank\",");
//			}
			json.append("\"temp\":\"111\"");// 没有实际用处，只是用于末尾的不加','的项
			if (tree.getChildList() != null && tree.getChildList().size() > 0) {
				json.append(",\"children\": [");
				json.append(appendJson(tree.getChildList()));

				if (json.toString().endsWith(",")) {
					json = new StringBuffer(json.subSequence(0, json.length() - 1));
				}
				json.append("]");
			}
			json.append("},");
		}
		return json;
	}

	/**
	 * 拼接菜单JSON内容(以前系统的模式)
	 *
	 * @param treeVO
	 * @param map_tempChild
	 * @return
	 */
	public StringBuffer getJsonTree(Tree treeVO, Map<String, String> map_tempChild) {
		StringBuffer jsonSbr = new StringBuffer();
		jsonSbr.append("{"); // 开始

		// attributes 部分
		jsonSbr.append("\"attributes\": { \"id\" : \"" + treeVO.getId() + "\",");
		jsonSbr.append("\"treeCode\":\"" + treeVO.getTree_code() + "\",");
		jsonSbr.append("\"nodeDeep\":\"" + treeVO.getNode_deep() + "\", ");
		jsonSbr.append("\"parentTreeCode\":\"" + treeVO.getParent_tree_code() + "\" ");
		jsonSbr.append("}, ");

		// data 部分
		jsonSbr.append("\"data\":{\"title\":\"" + treeVO.getNode_name() + "\", ");
//		if (!"".equals(StringUtil.getString(treeVO.getIcon_url()))) {
//			jsonSbr.append("\"icon\":\"" + treeVO.getIcon_url() + "\", ");
//		}
//		jsonSbr.append("\"attributes\":{\"href\":\"" + treeVO.getNode_url() + "\" ");

//		if (treeVO.getIs_quick() == 1) { // 是否用于打开新窗口
//			jsonSbr.append(",\"target\":\"_blank\" ");
//		}
		jsonSbr.append("}");
		jsonSbr.append("},");

		// children
		if (treeVO.getChildren_number() > 0 && map_tempChild.get(treeVO.getTree_code()) != null) { // 是否有子节点

			jsonSbr.append("\"state\" :\"open\","); // state 部分（当有子结点时展开）

			// 如果有子节点，则把子节点的 HTML 加入本节点
			jsonSbr.append("\"children\" : [");
			jsonSbr.append(HFMap.getIstance().getString(map_tempChild, treeVO.getTree_code()));
			jsonSbr.append("]");
		} else {
			jsonSbr.append("\"state\" :\"leaf\""); // state 部分（当无子结点时为叶状态）
		}

		jsonSbr.append("}");

		return jsonSbr;
	}

	// 读取树（管理页面所使用) TreeTable使用的格式
	public String getTreeTableHTML(String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		if (sWhere.length() > 0) {
			sWhere.append(" and ");
		}
		sWhere.append(" TREE_TYPE = ?");
		params.add(treeType);

		String orderBy = " order by node_deep desc, parent_tree_code, node_order asc ";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List<Tree> list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class,
				params.toArray());

		// 保存结果使用
		StringBuffer htmlSbr = new StringBuffer();
		// 临时数组（用于保存子结点信息）
		Map map_tempChild = new HashMap();
		// 临时父结点
		String tempParent = "null";

		Iterator<Tree> it = list.iterator();
		while (it.hasNext()) { // 遍历列表（树节点）
			Tree treeVO = it.next();

			// 判断是否是同一个父节点
			if (!tempParent.equals(treeVO.getParent_tree_code())) {
				/*
				 * 若不是同一个你节点，则先把之前所有的HTML存入 map, 清空 html, 更新父节点
				 */
				if (!"null".equals(tempParent)) {
					map_tempChild.put(tempParent, htmlSbr.toString());
				}
				htmlSbr.delete(0, htmlSbr.length());
				tempParent = treeVO.getParent_tree_code();
			}

			htmlSbr.append("<tr id='node-" + treeVO.getTree_code() + "' ");
			if (!"-1".equals(treeVO.getParent_tree_code())) { // 非顶级结点
				htmlSbr.append(" class='child-of-node-" + treeVO.getParent_tree_code() + "' ");
			}
			htmlSbr.append(">");
			htmlSbr.append("<td>");
			htmlSbr.append(treeVO.getNode_name() + "<span style='color:#ccc;''>(" + treeVO.getId() + ")</span>");
			htmlSbr.append("</td>");
			htmlSbr.append("<td style='padding:0; margin:0;'>");
			htmlSbr.append("<input type='checkbox' seq='" + treeVO.getId() + "' seqCode='" + treeVO.getTree_code()
					+ "' class='sClass' id='select_" + treeVO.getId() + "' name='select_" + treeVO.getTree_code()
					+ "' value='1' />");
			htmlSbr.append("</td>");
			htmlSbr.append("<td style='padding:0; margin:0;'>");
			htmlSbr.append("<input type='checkbox' seq='" + treeVO.getId() + "' seqCode='" + treeVO.getTree_code()
					+ "' class='dClass' id='disabled_" + treeVO.getId() + "' name='disabled_" + treeVO.getTree_code()
					+ "' value='1' />");
			htmlSbr.append("</td>");
			htmlSbr.append("</tr>");

			if (treeVO.getChildren_number() > 0 && map_tempChild.get(treeVO.getTree_code()) != null) { // 是否有子节点
				htmlSbr.append(HFMap.getIstance().getString(map_tempChild, treeVO.getTree_code()));
			}
		}
		return htmlSbr.toString();
	}

	// 读取树 ( 只返回树数据，让前台自己组装 )
	public List<Tree> getTypeTreeList(String treeType, boolean hasAuth, String userCode) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		if (sWhere.length() > 0) {
			sWhere.append(" and ");
		}
		sWhere.append(" TREE_TYPE=? and (IS_OPEN=1 OR IS_OPEN IS NULL) ");
		params.add(treeType);

		// 判断是否为超级管理员，如果为否，则加上访问限制，只有设置了权限的结点才能查看
		if (false && hasAuth && !UserUtil.isAdmin(userCode)) {

			User_account usersAccountVO = UserUtil.getUsersAccount(userCode);
			User_info userInfoVO = UserUtil.getUserInfo(userCode);

			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" exists (select 1 from (select node_seq, max(is_auth) as a, max(is_disabled) as d from "
					+ TableName.AUTH);
			sWhere.append("  where TREE_TYPE=? ");
			sWhere.append(" and ((OBJ_TYPE = 1 and OBJ_CODE=?) ");
//			if (!"".equals(StringUtil.getString(userVO.getUser_role()))) { // 当存在角色时，查询角色
//				sWhere.append(" OR (OBJ_TYPE = 3 and OBJ_CODE in (" + UserUtil.getSqlRoleCode(userVO.getUser_role())
//						+ ")) ");
//			}
//			if (!"".equals(StringUtil.getString(userInfoVO.getDept_seq_code()))) { // 当存在部门时，
//				// 查询部门
//				sWhere.append(" OR (OBJ_TYPE=2 and OBJ_CODE in ("
//						+ UserUtil.getSqlDeptCode(userInfoVO.getDept_seq_code()) + "))   )");
//			}
			sWhere.append(" group by node_seq) t2 where t2.node_seq=t1.seq and t2.a=1 and t2.d<>1 or t2.d is null)   ");

			params.add(treeType);
			params.add(userCode);
		}

		String orderBy = " order by node_deep asc, parent_tree_code, node_order asc "; // 先把父结点取出来

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List<Tree> list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class,
				params.toArray());
		return list;
	}

	/**
	 * 取新的流水号代码
	 */
	public String getNewSeqCode(String parentTreeCode, String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		sWhere.append(" TREE_TYPE = ? and PARENT_TREE_CODE=?  ");
		params.add(treeType);
		params.add(parentTreeCode);

		String orderBy = " order by NODE_ORDER asc";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class, params.toArray());

		if ("-1".equals(parentTreeCode)) {
			parentTreeCode = "";
		}

		String newSeqCode = "";
		boolean res = true;
		for (int i = 1; i < 1000; i++) {
			res = true;
			newSeqCode = parentTreeCode + HFString.getIstance().leftLengthString(i + "", 3, '0');
			Iterator<Tree> it = list.iterator();
			while (it.hasNext()) {
				Tree treeVO = it.next();
				if (newSeqCode.equals(treeVO.getTree_code())) {
					res = false;
					break;
				}
			}
			if (res) {
				break;
			}
		}

		return newSeqCode;
	}

	/**
	 * 对功能树子节点排序, 并返回最后的序号+1
	 */
	public int setChildNodeOrder(String parentTreeCode, long orderNum, String seqCode, String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		sWhere.append(" TREE_TYPE = ? and PARENT_TREE_CODE=?  ");
		params.add(treeType);
		params.add(parentTreeCode);

		String orderBy = " order by NODE_ORDER asc";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class, params.toArray());

		return treeDAO.setChildNodeOrder(list, orderNum, seqCode);
	}

	// 取得一个结点的信息
	public Tree getNodeInfo(String treeCode, String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();

		sWhere.append(" where TREE_TYPE = ? and TREE_CODE=?  ");
		params.add(treeType);
		params.add(treeCode);

		return HFDBHelper.read(TableName.TREE, sWhere.toString(), Tree.class, params.toArray());
	}

	// 取得一个结点的信息
	public List getNodeListByParent(String parentTreeCode, String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		sWhere.append(" TREE_TYPE = ? and TREE_CODE like ?  ");
		params.add(treeType);
		params.add(parentTreeCode + "%");

		String orderBy = " order by node_deep desc, parent_tree_code, node_order asc ";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class, params.toArray());
		return list;
	}

	// 取得一个结点的信息
	public long nodeDelete(String treeCode, String treeType) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();

		sWhere.append(" where TREE_TYPE = ? and TREE_CODE=?  ");
		params.add(treeType);
		params.add(treeCode);

		return HFDBHelper.delete(TableName.TREE, sWhere.toString(), params.toArray());
	}

	// 更新子结点的父结点
	public long updateChildrenSeqCode(String treeCode, String oldTreeCode, int deepDiff, String treeType)
			throws Exception {
		return treeDAO.updateChildrenSeqCode(treeCode, oldTreeCode, deepDiff, treeType);
	}

	/***************************** 下面方法非树管理使用 ******************************************/
	// 读取菜单树（快捷方式)
	public List getMenuTreeQuick(String treeType, boolean hasAuth, String userCode) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from " + TableName.TREE);

		sWhere.append(" IS_QUICK=1  and TREE_TYPE=? and (IS_OPEN=1 OR IS_OPEN IS NULL) ");
		params.add(treeType);

		// 判断是否为超级管理员，如果为否，则加上访问限制，只有设置了权限的结点才能查看
		if (false && hasAuth && !UserUtil.isAdmin(userCode)) {

			User_account usersAccountVO = UserUtil.getUsersAccount(userCode);
			User_info userInfoVO = UserUtil.getUserInfo(userCode);

			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" exists (select 1 from " + TableName.AUTH);
			sWhere.append("  where TREE_TYPE=? ");
			sWhere.append(" and ((OBJ_TYPE = 1 and OBJ_CODE=?) ");
//			if (!"".equals(StringUtil.getString(userVO.getUser_role()))) { // 当存在角色时，查询角色
//				sWhere.append(" OR (OBJ_TYPE = 3 and OBJ_CODE in (" + UserUtil.getSqlRoleCode(userVO.getUser_role())
//						+ ")) ");
//			}
//			if (!"".equals(StringUtil.getString(userInfoVO.getDept_seq_code()))) { // 当存在部门时，
//				// 查询部门
//				sWhere.append(" OR (OBJ_TYPE=2 and OBJ_CODE in ("
//						+ UserUtil.getSqlDeptCode(userInfoVO.getDept_seq_code()) + "))  ) ");
//			}
			sWhere.append(" group by node_seq) t2 where t2.node_seq=t1.seq and t2.a=1 and t2.d<>1 or t2.d is null)   ");

			params.add(treeType);
			params.add(userCode);
		}

		String orderBy = " order by parent_tree_code, node_order asc ";

		if (sWhere.length() > 0) {
			sql.append(" where ");
		}
		List list = HFDBHelper.querySql(sql.toString() + sWhere.toString() + orderBy, Tree.class, params.toArray());
		return list;

	}
}

